<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>VUE3</title>
  </head>
  <body>
    <div id="app"></div>

    <template id="tpl">
      <div>{{ info }}</div>
      <div>
        <button @click="changeInfo">改变整个info</button>
        <button @click="changeInfoName">改变info.name</button>
        <button @click="changeInfoNameReactStyle">改变info.name(REACT)</button>
      </div>
      <div>{{ msg }}</div>
    </template>

    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
      Vue.createApp({
        template: "#tpl",
        data() {
          return {
            info: {
              name: "张三",
              age: 18,
            },
            msg: "",
            t: null,
          };
        },
        methods: {
          changeInfo() {
            this.info = { name: "李四" };
          },
          changeInfoName() {
            this.info.name = "王五";
          },
          changeInfoNameReactStyle() {
            this.info = { ...this.info, name: "赵六" };
          },
        },
        watch: {
          /* // 简单方式，无法侦听对象深度改变
          info(newVal) {
            this.msg = `WATCH: 侦测到info发生改变：${JSON.stringify(newVal)}`;
          },
          */
          info: {
            handler(newVal) {
              this.msg = `WATCH: 侦测到info发生改变：${JSON.stringify(newVal)}`;
              this.t = setTimeout(() => {
                this.msg = "";
                clearTimeout(this.t);
                this.t = null;
              }, 3000);
            },
            deep: true, // 深度侦听
            immediate: true, // 立即执行（保证至少执行一次）
          },
        },
      }).mount("#app");
    </script>
  </body>
</html>
